package com.weilive.core.protocol.json;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.weilive.core.utils.ClassUtils;

public class JsonCodec {
	
	private static final Logger log = LoggerFactory.getLogger(JsonCodec.class);

	private static final HashMap<String, JsonRequestHandler> handlers = new HashMap<String, JsonRequestHandler>();
	
	public static void loadBySearch(String pkgName) {
		for (Class<?> c : ClassUtils.getClassList(pkgName, true, JsonRequestHandler.class)) {
			JsonRequestHandler handler;
			try {
				handler = (JsonRequestHandler)c.newInstance();
				handlers.put(handler.getRequestType().getSimpleName(), handler);
				log.info("===> load json handler:"+handler.getRequestType().getSimpleName());
			} catch (Exception e) {
			}
		}
	}
	
	public static void loadBySpring(ApplicationContext context) {
		for (JsonRequestHandler handler : context.getBeansOfType(JsonRequestHandler.class).values()) {
			handlers.put(handler.getRequestType().getSimpleName(), handler);
			log.info("===> load json handler:"+handler.getRequestType().getSimpleName());
		}
	}
	
	public static boolean isHandlerForTypeImplement(String type) {
		return handlers.containsKey(type);
	}

	public static JsonRequestHandler getHandlerByType(String type) {
		return handlers.get(type);
	}
}
